package controller

import (
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"shop-bean/constant"
	"shop-bean/model"
	"shop-bean/request"
	"shop-bean/vo"
	"shop-common/library/serializer"
	"shop-common/utils"
	"shop-common/utils/contextArgs"
	"shop-common/utils/pagehelper"
	"shop-common/utils/queryWrapper"
	"shop-service/business"
)

type ProductController struct {
}

// @Tags 商品列表、商品发布
// @description: 分页
// @Summary 分页
// @Security ApiKeyAuth
// @function: Page
// @Accept  json
// @Produce  json
// @Param current query string false "当前页，默认1"
// @Param size query string false "每页大小，默认10"
// @Param keyword query string false "keyword"
// @Param status query int true "status"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/product/page [get]
func (p *ProductController) Page(ctx *gin.Context) {
	form := pagehelper.SearchPageRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	shopId, err := contextArgs.GetSHopId(ctx)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	paginator := pagehelper.New().SetOffset(form).SetFilter([]string{"prod_id"}).
		IsPush(form.Keyword != "", queryWrapper.Like("prod_name", form.Keyword)).
		Push(queryWrapper.Eq("shop_id", shopId)).
		IsPush(form.Status > 0, queryWrapper.Eq("status", form.Status)).
		Paginator()

	page, err := business.ServiceImpl().ProductService.FindPage(ctx, paginator)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", page)
}

// @Tags 商品列表、商品发布
// @description: 获取信息
// @Summary 获取信息
// @Security ApiKeyAuth
// @function: Info
// @Accept  json
// @Produce  json
// @Param prodId path int true "商品id"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/product/info/{prodId} [get]
func (p *ProductController) Info(ctx *gin.Context) {
	shopId, err := contextArgs.GetSHopId(ctx)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	prodId, err := contextArgs.GetUriIntPath(ctx, "prodId")
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	product, err := business.ServiceImpl().ProductService.FindById(uint(prodId))
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	if product == nil {
		serializer.SuccessData(ctx, "", nil)
		return
	}

	if product.ShopId != shopId {
		serializer.Fail(ctx, "没有权限获取该商品规格信息")
		return
	}

	tagList, err := business.ServiceImpl().ProdTagReferenceService.ListTagIdByProdId(ctx, product.ProdId)
	if err != nil {
		serializer.SuccessData(ctx, "", nil)
		return
	}

	var productVO *vo.ProductVO
	utils.StructMap(product, &productVO)
	productVO.TagList = tagList

	serializer.SuccessData(ctx, "", productVO)
}

// @Tags 商品列表、商品发布
// @description: 保存
// @Summary 保存
// @Security ApiKeyAuth
// @function: Save
// @accept application/json
// @Produce application/json
// @Param data body request.ProductRequest true "新增商品"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/product [post]
func (p *ProductController) Save(ctx *gin.Context) {
	form := request.ProductRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err := checkRequest(&form)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	prodId, err := business.ServiceImpl().ProductService.Create(ctx, &form)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicCreateErr)
		return
	}

	serializer.SuccessData(ctx, "", prodId)

}

// @Tags 商品列表、商品发布
// @description: 修改
// @Summary 修改
// @Security ApiKeyAuth
// @function: Update
// @accept application/json
// @Produce application/json
// @Param data body request.ProductRequest true "修改商品"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /prod/product [put]
func (p *ProductController) Update(ctx *gin.Context) {
	form := request.ProductRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if form.ProdId < 1 {
		serializer.Fail(ctx, "商品Id不能为空")
		return
	}

	dbProduct, err := business.ServiceImpl().ProductService.FindById(form.ProdId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	shopId, err := contextArgs.GetSHopId(ctx)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	if dbProduct.ShopId != shopId {
		serializer.Fail(ctx, "无法修改非本店铺商品信息")
		return
	}

	err = business.ServiceImpl().ProductService.Update(ctx, &form, dbProduct)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	serializer.SuccessData(ctx, "", dbProduct.ProdId)
}

func checkRequest(req *request.ProductRequest) error {
	if len(req.TagList) == 0 {
		return errors.New("请选择产品分组")
	}

	//if !req.DeliveryMode.HasShopDelivery && !req.DeliveryMode.HasUserPickUp {
	//	return errors.New("请选择配送方式")
	//}

	isAllUnUse := true
	for _, sku := range req.SkuList {
		if sku.Status == constant.GLOBAL_ENABLE {
			isAllUnUse = false
			break
		}
	}

	if isAllUnUse {
		return errors.New("至少要启用一种商品规格")
	}
	return nil
}

// @Tags 商品列表、商品发布
// @description: 删除
// @Summary 删除
// @Security ApiKeyAuth
// @function: Delete
// @Accept  json
// @Produce  json
// @Param data body request.CommonBatchRequest true "请求参数"
// @Success 200 {object} string "{"code":0," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shop/pickAddr [delete]
func (p *ProductController) Delete(ctx *gin.Context) {
	form := request.CommonBatchRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	for _, id := range form.Ids {
		dbProduct, err := verifyDbProduct(ctx, id)
		if err != nil {
			serializer.Fail(ctx, err.Error())
			return
		}
		if err := business.ServiceImpl().ProductService.Delete(ctx, dbProduct); err != nil {
			serializer.Fail(ctx, fmt.Sprintf("产品名字= %s 删除失败", dbProduct.ProdName))
			return
		}
	}

	serializer.Success(ctx, "")
}

func verifyDbProduct(ctx *gin.Context, prodId uint) (*model.Product, error) {
	if prodId < 1 {
		return nil, errors.New("商品Id不能为空")
	}

	dbProduct, err := business.ServiceImpl().ProductService.FindById(prodId)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("%s", serializer.PublicQueryErr))
	}

	shopId, err := contextArgs.GetSHopId(ctx)
	if err != nil {
		serializer.Fail(ctx, err.Error())
		return nil, err
	}

	if dbProduct.ShopId != shopId {
		return nil, errors.New("无法修改非本店铺商品信息")
	}

	if dbProduct.Status == constant.GLOBAL_ENABLE {
		return nil, errors.New(fmt.Sprintf("产品名字= %s 商品未下架不能刪除", dbProduct.ProdName))
	}

	//if len(dbProduct.SkuList) > 0 {
	//	for _, sku := range dbProduct.SkuList {
	//		if sku.Status == 2 {
	//			return nil, errors.New(fmt.Sprintf("产品名字= %s 商品规格未禁用不能刪除", dbProduct.ProdName))
	//		}
	//	}
	//}

	return dbProduct, nil
}
